<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * user_policies_service.php
 *
 * @author  :  Skiychan <developer@zzzzy.com>
 * @created :  2015/4/22
 * @modified:  
 * @version :  0.0.1
 */
class User_policies_service extends MY_Service {

    public function __construct() {
        parent::__construct();
        $this->load->model('user_policies_model');
        $this->load->model('user_files_model');
    }

    /**
     * 取得策略
     * @param $uid int userid
     * @param $type int file type
     * @param $fid int file id
     * @return bool
     */
    public function get_policy($uid, $type, $fid) {
        if (empty($fid) || !is_numeric($type) || empty($uid)) return $this->set_error(1003);

        if($type == 1) {
            return $this->user_files_model->get_folder_info($uid, $fid);
        } else {
            return $this->user_files_model->get_file_info($uid, $fid, TRUE);
        }
    }
    /**
     * 获取文件夹的子目录/或文件
     * @param $uid 用户id
     * @param $ids 文件/文件夹的ID
     * @param bool $all 是否查找所以子节点
     * @param $type 类型 1file,2folder
     * @param $policy_field 策略字段
     * @return array|null
     */
    public function get_children($uid, $ids, $type, $all=TRUE, $policy_field="data") {
        if (empty($uid) || empty($ids) || empty($type)) return $this->set_error(1003);

        if ($type == 1) {
            return $this->user_files_model->get_folder_files($uid, $ids, $all, "id,access_denied", $policy_field);
        } else {
            return $this->user_files_model->get_folder_children($uid, $ids, $all, "id,access_denied", $policy_field);
        }
    }


    //返回文件夹下面的文件个数
    public function get_folder_file_count($uid,$folder_id=0)
    {
        return $this->user_files_model->get_folder_file_count($uid,$folder_id);
    }

    /**
     * 获取文件/文件夹的策略及授权
     * @param $uid
     * @param $ids
     * @param int $ac access_denied的值 0授权/1拒绝/其它全部
     * @param int $ftype 1文件/2文件夹/其它
     * @param bool $po
     * @return null
     */
    public function get_access_info($uid, $ids, $ac=1, $ftype=1, $po=FALSE) {
        if (empty($uid) || empty($ids)) return NULL;

        $data = $this->user_policies_model->get_access_info($uid, $ids, $ac, $ftype, $po);
        if (! $data) return NULL;

        return $data;
    }

    /**
     * 取文件/文件夹的策略及受控信息
     * @param $uid 用户id
     * @param $file_uuids 文件列表id列表
     * @param $folder_uuids 文件夹id列表
     * @param bool $children 子孙目录
     * @return array|string
     */
    public function get_data_info($uid, $file_uuids, $folder_uuids, $children=FALSE) {
        if (empty($uid) && (empty($file_uuids) && empty($folder_uuids)))
        {
            return Common::prf_json(FALSE,NULL,NULL,time(),TRUE,"f_id is null");
        }

        $file_list = array();
        //提交有文件
        if (! empty($file_uuids)) {
            $files = $this->user_policies_model->get_access_info($uid, $file_uuids, 3, 1, TRUE);
            if ($files) $file_list = $files;
        }

        //所有子目录及文件
        //$children = true;
        //var_dump(array('a'=>$file_list));exit;
        //提交有文件夹
        if (! empty($folder_uuids))
        {

            //取子(子孙)文件列表
            $file_list2 = $this->user_files_model->get_folder_files($uid, $folder_uuids, $children, "id,access_denied", "data");
            //取子孙目录列表
            if ($children) {
                $folder_list =  $this->user_files_model->get_folder_children($uid, $folder_uuids, $children, "id,access_denied", "data");
            } else {
                $folder_list = $this->user_policies_model->get_access_info($uid, $folder_uuids, 3, 2, TRUE);
            }
            //合并文件
            if ($file_list2) {
                $file_list = array_merge($file_list, $file_list2);
            }
        }
        $result = array();
        if (isset($file_list) && ! empty($file_list)) $result['files'] = $file_list;
        if (isset($folder_list) && ! empty($folder_list)) $result['folders'] = $folder_list;
        //var_dump(array('a'=>$result));exit;
        //var_dump(array('a'=>$result));exit;

        return $result;
    }

    /**
     * access_denied信息
     * @param $uid
     * @param $file_uuids 文件列表
     * @param $folder_uuids 文件夹列表
     * @param int $ac access_denied值  0/1 或其它
     * @param bool $children 是否获取子孙目录的文件及文件夹
     * @return array|string 返回access_denied值对应的id
     */
    public function get_data_access_denied($uid, $file_uuids, $folder_uuids, $ac=1, $children=FALSE) {
        if (empty($uid) && (empty($file_uuids) && empty($folder_uuids)))
            return Common::prf_json(FALSE,NULL,NULL,time(),TRUE,"f_id is null");

        $file_list = array();
        //提交有文件
        if (! empty($file_uuids)) {
            $files = $this->user_policies_model->get_access_info($uid, $file_uuids, $ac, 1);
            if ($files) $file_list = $files;
        }

        //所有子目录及文件
        //$children = true;

        //提交有文件夹
        if (! empty($folder_uuids)) {
            //取子(子孙)文件列表
            $file_list2 = $this->user_files_model->get_folder_files($uid, $folder_uuids, $children, "id,access_denied");

            //取子孙目录列表
            if ($children) {
                $folder_list =  $this->user_files_model->get_folder_children($uid, $folder_uuids, $children, "id,access_denied");
            } else {
                $folder_list = $this->user_policies_model->get_access_info($uid, $folder_uuids, $ac, 2);
            }

            //合并文件
            if ($file_list2) {
                $file_list = array_merge($file_list, $file_list2);
            }
        }

        $result = array();
        if (isset($folder_list)) {
            foreach ($folder_list as $v) {
                if (($ac == 1) || ($ac == 0)) {
                    if ($v['access_denied'] == $ac)
                        $result['folders'][] = $v['id'];
                } else {
                    $result['folders'][] = $v['id'];
                }
            }
        }
        if (isset($file_list)) {
            foreach ($file_list as $v) {
                if (($ac == 1) || ($ac == 0)) {
                    if ($v['access_denied'] == $ac)
                        $result['files'][] = $v['id'];
                } else {
                    $result['files'][] = $v['id'];
                }
            }
        }

        return $result;
    }

    /**
     * 传一组文件id获取文件的授权
     * @param $uid
     * @param $ids
     * @param int $ac
     * @param int $ftype
     * @param bool $po
     * @return array|null
     */
    public function get_access_denied($uid, $ids, $ac=1, $ftype=1) {
        if (empty($uid) || empty($ids)) return NULL;

        $data = $this->get_access_info($uid, $ids, $ac, $ftype);
        if (! $data) return NULL;

        $newIds = array();
        foreach ($data as $keys => $values) {
            $newIds[] = $values['id'];
        }
        return $newIds;
    }

    /**
     * 获取策略描述
     * @param null $desc 具体描述
     * @return array
     */
    public function get_base_policies($desc = NULL) {
        $data = array (
            1 => array ('description' => 'open_counter', 'priority' => 4, 'phase' => 5, 'catagory' => 1),
            2 => array ('description' => 'life_span', 'priority' => 3, 'phase' => 3, 'catagory' => 1),
            3 => array ('description' => 'delete_after_expired', 'priority' => 5, 'phase' => 3, 'catagory' => 2),
            4 => array ('description' => 'access_denied', 'priority' => 1, 'phase' => 3, 'catagory' => 1),
            5 => array ('description' => 'read_pwd', 'priority' => 2, 'phase' => 3, 'catagory' => 1)
        );

        if (! empty($desc) && isset($data[$desc]))
            return $data[$desc];

        return $data;
    }

    /**
     * @param $uid
     * @param $type
     * @param $fid
     * @param $sub_policies
     * @param $mod_val
     * @return bool
     */
    public function add_policy($uid, $type, $fid, $sub_policies, $mod_val) {
        if (empty($uid) || empty($type) || empty($fid) || empty($sub_policies))
            return $this->set_error(1003);
        //将sub
        $data = array(
            'ftype' => $type,
            'fid' => $fid,
            'data' => json_encode($sub_policies),
            'is_global' => 1,
            'creation_ts' => time(),
            'modify_ts' => time(),
            'expiration_ts' => $sub_policies[1]['value_set'],
            'expired' => 0
        );
        //删除原有策略
        $this->del_policy_nts($type, $fid);
        //添加新策略
        $resp = $this->user_policies_model->add_policy($uid, $data);

        #添加、更新策略成功
        if (! empty($resp)) {
            //如果是文件,且有修改策略则添加轨迹
            if (($type == 1) && (count($mod_val) > 0)) {
                $this->add_trace($uid, $fid, $mod_val);
            }
        }

        return $resp;
    }

    /**
     * 添加轨迹
     * @param $uid
     * @param $fid
     * @param $traces
     */
    public function add_trace($uid, $fid, $traces) {
        $this->load->library('traces');
        $trace_list = array();
        foreach ($traces as $keys => $values) {
            $trace_list[] = array(
                'file_id' => $fid,
                'event' => Traces::get_policy_event($values['des']),
                'start' => $values['start'],
                'end' => $values['end'],
                'actor' => $uid
            );
        }
        Traces::trace_file($trace_list, Traces::EVENT_SET_POLICY);
    }

    /**
     * 添加策略与轨迹
     * @param $file 文件
     * @param $type 类型 1为文件,则添加轨迹; 2为文件夹,不添加轨迹
     * @param $n_policy array()
     */
    public function add_policies($file, $type, $n_policy) {
        if (empty($file) || empty($n_policy))
            return $this->set_error(1003);

        //提出策略,转成数组形式
        $file_policy = json_decode($file['data'], true);
        //更改的信息,轨迹使用
        $mod_val = array();
        //文件 添加轨迹,文件夹不添加轨迹
        if ($type == 1) {
            //全新策略
            if (! $file_policy) {
                foreach ($n_policy as  $k => $v) {
                    //如果值不为空
                    if (!empty($v['value_set'])) {
                        $mod_val[] = array(
                            'des' => $v['des'],
                            'start' => 0,
                            'end' => $v['value_set']
                        );
                    }
                }

            //有旧策略
            } else {
                $old_count = count($file_policy);
                //新策略遍历
                foreach ($n_policy as  $k => $v) {
                    //$tag = FALSE;  //标识策略
                    //旧策略遍历
                    foreach ($file_policy as $key => $val) {
                        //相同的项
                        if ($v['des'] === $val['des']) {
                            //有改变,有则添加至
                            if (($v['value_set'] != $val['value_set'])) {
                                $mod_val[] = array(
                                    'des' => $v['des'],
                                    'start' => $val['value_set'],
                                    'end' => $v['value_set']
                                );
                            } else {
                                /*
                                #访问控制次数重置
                                if (($v['des'] == "open_counter") &&
                                    ($v['value'] != $val['value'])) {
                                    $mod_val[] = array(
                                        'des'   => $v['des'],
                                        'start' => $val['value_set'],
                                        'end'   => $val['value_set']
                                    );
                                }*/
                            }

                            //$tag = TRUE;
                            break 1;
                        }
                        //尾数
                        if ($key == ($old_count - 1) && !empty($v['value_set'])) {
                            $mod_val[] = array(
                                'des' => $v['des'],
                                'start' => '',
                                'end' => $v['value_set']
                            );
                        }
                    }
                }
            }
        }
        //添加策略
        $this->add_policy($file['uid'], $type, $file['id'], $n_policy, $mod_val);
    }

    /**
     * 更新策略信息
     * @param $fid
     * @param $ftype 类型
     * @param array $policy 策略数组
     * @return null
     */
    public function update_policy($fid, $ftype, $policy=array(), $value=NULL) {
        if (empty($fid) || empty($ftype)) return NULL;

        return $this->user_policies_model->update_policy($fid, $ftype, $policy, $value);
    }
    /**
     * 删除策略
     * @param $uid userid
     * @param $type int file_type 1files,2folder
     * @param $fid int file_id
     * @return null
     */
    public function del_policy($uid, $type, $fid) {
        if (empty($fid) || empty($uid)) return $this->set_error(1003);

        return $this->user_policies_model->del_policy($uid, $type, $fid);
    }

    public function del_policy_nts($type,$fid)
    {
        if (empty($fid)) return $this->set_error(1003);

        return $this->user_policies_model->del_policy_nts($type, $fid);
    }

    /**
     * 将json格式的策略转换成数组 k=>v 形式
     * @param $str 策略json格式的数据
     * @return array
     */
    public function policy_to_arr($str) {
        $arr = json_decode($str, true);
        $result = array();
        foreach ($arr as $key => $value) {
            $result[$value['des']] = $value['value_set'];
        }
        return $result;
    }
}

/* End of file user_policies_service.php */
/* Location: ./ */